import React from 'react';
import { Card, Form, Input, Select, Button, Space, Table, Tag, Modal, message, Drawer, Tree, Checkbox, Typography, Divider } from 'antd';
import { PlusOutlined, EditOutlined, KeyOutlined, UserOutlined, LinkOutlined, CopyOutlined, SafetyCertificateOutlined } from '@ant-design/icons';

const { Option } = Select;
const { Text } = Typography;

// 模拟角色与时区字典
const ROLE_OPTIONS = [
  { label: '管理员', value: 'admin' },
  { label: '运营', value: 'ops' },
  { label: '财务', value: 'finance' },
  { label: '访客', value: 'guest' },
];
const TIMEZONES = [
  { label: 'Asia/Shanghai (UTC+8)', value: 'Asia/Shanghai' },
  { label: 'UTC (UTC+0)', value: 'UTC' },
  { label: 'America/New_York (UTC-4)', value: 'America/New_York' },
  { label: 'Europe/Berlin (UTC+2)', value: 'Europe/Berlin' },
];

// 模拟菜单树（权限）
const MENU_TREE = [
  { title: '仪表盘', key: 'dashboard' },
  {
    title: '系统', key: 'system', children: [
      { title: '邮箱配置', key: 'system-email' },
      { title: 'App版本', key: 'system-app' },
      { title: '用户管理', key: 'system-user' },
      { title: '凭证管理', key: 'system-certificate' },
    ]
  },
  { title: '订单', key: 'orders' },
  { title: '设备', key: 'device' },
];
const POWER_LIST = ['查询', '新增', '编辑', '删除', '导出', '导入'];

// 随机生成初始用户
export default function UserPage() {
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [domainForm] = Form.useForm();
  const [loading, setLoading] = React.useState(false);
  const [users, setUsers] = React.useState(() => {
    const saved = localStorage.getItem('sys-users');
    if (saved) return JSON.parse(saved);
    const now = Date.now();
    return Array.from({ length: 20 }).map((_, i) => ({
      id: i + 1,
      createName: i % 3 === 0 ? '张三' : i % 3 === 1 ? '李四' : '王五',
      userName: `user_${i + 1}`,
      domainName: `example${i + 1}.com`,
      roleList: i % 4 === 0 ? ['admin'] : i % 4 === 1 ? ['ops'] : i % 4 === 2 ? ['finance'] : ['guest'],
      nickName: `昵称-${i + 1}`,
      phone: `1380000${String(100 + i).slice(-3)}`,
      timeZone: TIMEZONES[i % TIMEZONES.length].value,
      email: `user${i + 1}@mail.com`,
      insertType: i % 2 === 0 ? 1 : 2, // 1 管理员注册, 2 用户注册
      createTime: new Date(now - i * 86400000).toLocaleString(),
      stripeCus: i % 5 === 0 ? '' : `cus_${Math.random().toString(36).slice(2, 10)}`,
      permissions: { menus: ['dashboard'], powers: ['查询'] },
    }));
  });
  const [filtered, setFiltered] = React.useState(users);

  const [editOpen, setEditOpen] = React.useState(false);
  const [domainOpen, setDomainOpen] = React.useState(false);
  const [permOpen, setPermOpen] = React.useState(false);
  const [current, setCurrent] = React.useState(null);
  const [checkedMenus, setCheckedMenus] = React.useState([]);
  const [checkedPowers, setCheckedPowers] = React.useState([]);

  React.useEffect(() => {
    localStorage.setItem('sys-users', JSON.stringify(users));
    setFiltered(users);
  }, [users]);

  const handleSearch = () => {
    const { userName, nickName, role, insertType } = form.getFieldsValue();
    const res = users.filter((u) => {
      const matchUser = userName ? u.userName.toLowerCase().includes(userName.toLowerCase()) : true;
      const matchNick = nickName ? u.nickName.toLowerCase().includes(nickName.toLowerCase()) : true;
      const matchRole = role ? u.roleList.includes(role) : true;
      const matchInsertType = insertType ? u.insertType === insertType : true;
      return matchUser && matchNick && matchRole && matchInsertType;
    });
    setFiltered(res);
  };

  const onReset = () => {
    form.resetFields();
    setFiltered(users);
  };

  const roleLabels = (roles) => roles.map((r) => ROLE_OPTIONS.find((o) => o.value === r)?.label || r).join(' / ');
  const timeZoneLabel = (tz) => TIMEZONES.find((t) => t.value === tz)?.label || tz;

  const copyText = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      message.success('已复制到剪贴板');
    } catch (e) {
      message.warning('复制失败，请手动选择复制');
    }
  };

  const openEdit = (record) => {
    setCurrent(record || null);
    setEditOpen(true);
    editForm.setFieldsValue(record || { timeZone: TIMEZONES[0].value, roleList: ['guest'] });
  };

  const openDomain = (record) => {
    setCurrent(record);
    setDomainOpen(true);
    domainForm.setFieldsValue({ domainName: record.domainName });
  };

  const openPerm = (record) => {
    setCurrent(record);
    setPermOpen(true);
    setCheckedMenus(record.permissions?.menus || []);
    setCheckedPowers(record.permissions?.powers || []);
  };

  const saveUser = async () => {
    try {
      const values = await editForm.validateFields();
      setUsers((prev) => {
        if (!current) {
          const id = Date.now();
          return [{ id, createName: 'Admin', insertType: 1, createTime: new Date().toLocaleString(), stripeCus: '', permissions: { menus: ['dashboard'], powers: ['查询'] }, ...values }, ...prev];
        }
        return prev.map((u) => (u.id === current.id ? { ...u, ...values } : u));
      });
      setEditOpen(false);
      message.success('用户信息已保存（本地模拟）');
    } catch (e) {}
  };

  const saveDomain = async () => {
    try {
      const { domainName } = await domainForm.validateFields();
      setUsers((prev) => prev.map((u) => (u.id === current.id ? { ...u, domainName } : u)));
      setDomainOpen(false);
      message.success('域名已更新');
    } catch (e) {}
  };

  const savePerm = () => {
    if (!current) return;
    setUsers((prev) => prev.map((u) => (u.id === current.id ? { ...u, permissions: { menus: checkedMenus, powers: checkedPowers } } : u)));
    setPermOpen(false);
    message.success('权限已分配（本地模拟）');
  };

  const resetPassword = (record) => {
    Modal.confirm({
      title: '重置密码确认',
      content: `确定要重置用户 ${record.userName} 的密码吗？操作将设置为默认值 123456。`,
      onOk: () => message.success('密码已重置为 123456（本地模拟）'),
    });
  };

  const createStripe = (record) => {
    if (record.stripeCus) return message.info('该用户已存在 Stripe 客户标识');
    setUsers((prev) => prev.map((u) => (u.id === record.id ? { ...u, stripeCus: `cus_${Math.random().toString(36).slice(2, 10)}` } : u)));
    message.success('已为该用户创建 Stripe 客户（本地模拟）');
  };

  const columns = [
    { title: '创建人', dataIndex: 'createName', key: 'createName', width: 100 },
    { title: '用户名', dataIndex: 'userName', key: 'userName', width: 160, render: (text) => (
      <Space>
        <Text>{text}</Text>
        <Button size="small" type="link" icon={<CopyOutlined />} onClick={() => copyText(text)}>复制</Button>
      </Space>
    ) },
    { title: '域名', dataIndex: 'domainName', key: 'domainName', width: 220, render: (_, record) => (
      <Space>
        <Text>{record.domainName}</Text>
        <Button size="small" type="link" icon={<CopyOutlined />} onClick={() => copyText(record.domainName)}>复制</Button>
        <Button size="small" type="link" icon={<EditOutlined />} onClick={() => openDomain(record)}>编辑</Button>
      </Space>
    ) },
    { title: '角色', dataIndex: 'roleList', key: 'roleList', width: 160, render: (roles) => (
      roles.map((r) => <Tag key={r} color={r === 'admin' ? 'blue' : r === 'ops' ? 'green' : r === 'finance' ? 'orange' : 'default'}>{ROLE_OPTIONS.find((o) => o.value === r)?.label || r}</Tag>)
    ) },
    { title: '昵称', dataIndex: 'nickName', key: 'nickName', width: 120 },
    { title: '电话', dataIndex: 'phone', key: 'phone', width: 140 },
    { title: '时区', dataIndex: 'timeZone', key: 'timeZone', width: 200, render: (tz) => timeZoneLabel(tz) },
    { title: '邮箱', dataIndex: 'email', key: 'email', width: 220 },
    { title: '来源', dataIndex: 'insertType', key: 'insertType', width: 120, render: (v) => (
      v === 1 ? <Tag color="blue">管理员注册</Tag> : <Tag color="purple">用户注册</Tag>
    ) },
    { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 200 },
    { title: 'Stripe', dataIndex: 'stripeCus', key: 'stripeCus', width: 200, render: (s) => (s ? <Tag color="green">{s}</Tag> : <Tag>未创建</Tag>) },
    { title: '操作', key: 'actions', fixed: 'right', width: 300, render: (_, record) => (
      <Space size="small" wrap>
        <Button icon={<EditOutlined />} onClick={() => openEdit(record)}>编辑</Button>
        <Button icon={<KeyOutlined />} onClick={() => resetPassword(record)}>重置密码</Button>
        <Button icon={<SafetyCertificateOutlined />} onClick={() => openPerm(record)}>权限设置</Button>
        <Button icon={<LinkOutlined />} onClick={() => window.open(`/#/user/${record.id}`, '_blank')}>跳转</Button>
        <Button type="primary" disabled={!!record.stripeCus} onClick={() => createStripe(record)}>创建Stripe</Button>
      </Space>
    ) },
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <Card title="用户管理" extra={<Space>
        <Button type="primary" icon={<PlusOutlined />} onClick={() => openEdit(null)}>新增用户</Button>
      </Space>} variant="outlined">
        <Form form={form} layout="inline" onFinish={handleSearch} style={{ rowGap: 12 }}>
          <Form.Item label="用户名" name="userName">
            <Input allowClear placeholder="输入用户名关键词" style={{ width: 220 }} />
          </Form.Item>
          <Form.Item label="昵称" name="nickName">
            <Input allowClear placeholder="输入昵称关键词" style={{ width: 220 }} />
          </Form.Item>
          <Form.Item label="角色" name="role">
            <Select allowClear placeholder="选择角色" style={{ width: 180 }}>
              {ROLE_OPTIONS.map((r) => <Option key={r.value} value={r.value}>{r.label}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="来源" name="insertType">
            <Select allowClear placeholder="选择来源" style={{ width: 160 }}>
              <Option value={1}>管理员注册</Option>
              <Option value={2}>用户注册</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button onClick={onReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`用户列表（共 ${filtered.length} 条）`} variant="outlined">
        <Table
          rowKey="id"
          dataSource={filtered}
          loading={loading}
          columns={columns}
          scroll={{ x: 1400 }}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 编辑/新增 用户 */}
      <Modal
        open={editOpen}
        title={current ? '编辑用户' : '新增用户'}
        okText="保存"
        cancelText="取消"
        onOk={saveUser}
        onCancel={() => setEditOpen(false)}
        width={640}
      >
        <Form form={editForm} layout="vertical">
          <Form.Item label="用户名" name="userName" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="例如：user_001" />
          </Form.Item>
          <Form.Item label="昵称" name="nickName" rules={[{ required: true, message: '请输入昵称' }]}>
            <Input placeholder="例如：小明" />
          </Form.Item>
          <Form.Item label="邮箱" name="email" rules={[{ type: 'email', message: '邮箱格式不正确' }]}>
            <Input placeholder="例如：user@mail.com" />
          </Form.Item>
          <Form.Item label="电话" name="phone">
            <Input placeholder="例如：13800001234" />
          </Form.Item>
          <Form.Item label="时区" name="timeZone" rules={[{ required: true, message: '请选择时区' }]}>
            <Select>
              {TIMEZONES.map((t) => <Option key={t.value} value={t.value}>{t.label}</Option>)}
            </Select>
          </Form.Item>
          <Form.Item label="角色" name="roleList" rules={[{ required: true, message: '请选择至少一个角色' }]}>
            <Select mode="multiple" allowClear>
              {ROLE_OPTIONS.map((r) => <Option key={r.value} value={r.value}>{r.label}</Option>)}
            </Select>
          </Form.Item>
          <Divider />
          <Form.Item label="域名" name="domainName">
            <Input placeholder="例如：example.com" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑域名 */}
      <Modal
        open={domainOpen}
        title="编辑域名"
        okText="保存"
        cancelText="取消"
        onOk={saveDomain}
        onCancel={() => setDomainOpen(false)}
        width={480}
      >
        <Form form={domainForm} layout="vertical">
          <Form.Item label="域名" name="domainName" rules={[{ required: true, message: '请输入域名' }]}>
            <Input placeholder="例如：example.com" />
          </Form.Item>
        </Form>
      </Modal>

      {/* 权限设置 */}
      <Drawer
        open={permOpen}
        title={current ? `权限设置 - ${current.userName}` : '权限设置'}
        width={520}
        onClose={() => setPermOpen(false)}
        extra={<Space>
          <Button type="primary" onClick={savePerm}>保存</Button>
          <Button onClick={() => setPermOpen(false)}>关闭</Button>
        </Space>}
      >
        <Space direction="vertical" style={{ width: '100%' }} size={16}>
          <Card title="菜单权限" size="small" variant="outlined">
            <Tree
              checkable
              treeData={MENU_TREE}
              checkedKeys={checkedMenus}
              onCheck={(keys) => setCheckedMenus(keys)}
            />
          </Card>
          <Card title="功能权限" size="small" variant="outlined">
            <Checkbox.Group
              options={POWER_LIST}
              value={checkedPowers}
              onChange={(vals) => setCheckedPowers(vals)}
            />
          </Card>
        </Space>
      </Drawer>
    </div>
  );
}